<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="预警类型" prop="warnType">
        <el-select
          v-model="queryParams.warnType"
          placeholder="请选择预警类型"
          clearable
          class="!w-240px"
          @change="handleQuery"
        >
          <el-option key="1" label="围栏预警" value="1"/>
          <el-option key="2" label="聚集预警" value="2"/>
          <el-option key="3" label="出入杭预警" value="3"/>
          <el-option key="4" label="接入预警" value="4"/>
          <el-option key="5" label="失轨预警" value="5"/>
          <el-option key="6" label="购物异常" value="6"/>
          <el-option key="7" label="言论预警" value="7"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px"/>
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px"/>
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column
        label="预警类型"
        align="center"
        prop="warnTypeText"
        width="100px"
      />
      <el-table-column
        label="触网时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="175px"
      />
      <el-table-column
        label="预警时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="175px"
      />
      <el-table-column label="预警内容" align="left" prop="warningContent" min-width="440px"/>
      <el-table-column label="地图详情" align="center" min-width="80px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="handleDetailClick(scope.row)"
          >
            看详情
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        label="状态"
        align="center"
        prop="isRead"
        width="140px"
      >
        <template #header>
          <div style="display: flex; align-items: center; justify-content: center;">
            <span>状态</span>
            <el-button
              type="text"
              size="small"
              style="margin-left: 30px; color: #409EFF;"
              @click="handleMarkAllRead"
              :disabled="!list.length"
            >
              全选
            </el-button>
          </div>
        </template>
        <template #default="scope">
          <!-- 核心：用一个 inline-flex 容器包裹所有元素，实现一行排列 + 垂直居中 -->
          <div style="display: inline-flex; align-items: center;">
            <!-- 未读状态：图标+文字 -->
            <template v-if="!scope.row.isRead">
              <el-icon color="#F56C6C" size="18">
                <Message/>
              </el-icon>
              <span style="margin-left: 6px; color: #F56C6C;">未读</span>
            </template>

            <!-- 已读状态：图标+文字 -->
            <template v-else-if="scope.row.isRead">
              <el-icon color="#67C23A" size="18">
                <Check/>
              </el-icon>
              <span style="margin-left: 6px; color: #67C23A;">已读</span>
            </template>

            <!-- 阅读按钮：仅未读显示，与状态在同一行 -->
            <el-button
              v-if="!scope.row.isRead"
              type="text"
              size="small"
              style="margin-left: 12px; color: #409EFF;"
              @click="handleMarkSingleRead(scope.row)"
            >
              阅读
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 地图弹窗 -->
  <el-dialog
    v-model="showMapDialog"
    title="预警点地图详情"
    :width="'70%'"
    :max-height="'90vh'"
    :fullscreen="false"
    :close-on-click-modal="false"
    ref="mapDialogRef"
    class="draggable-dialog fixed-size-dialog"
  >
    <div class="map-dialog-container">
      <div id="map" ref="mapRef" class="map"></div>
    </div>
  </el-dialog>

</template>

<script setup lang="ts">
import {ref, reactive, watch, nextTick, onMounted, onUnmounted} from 'vue'
import {dateFormatter} from '@/utils/formatTime'
import L from 'leaflet'
import 'leaflet/dist/leaflet.css'
import 'leaflet-draw/dist/leaflet.draw.css'
import 'leaflet-draw'
import {MapPolygonApi} from '@/api/member/map/mapConfigApi'
import {WarningIndividualApi, WarningIndividualVO} from '@/api/member/warningindividual'
import Pagination from '@/components/Pagination/index.vue'
import {ElMessage} from 'element-plus'
import {formatToDateTime} from "@/utils/dateUtil";
import {Check, Message} from "@element-plus/icons-vue";
import {WarnConfigListVo, WarnConfigRespVO, WarningGatherApi} from "@/api/member/warninggather";
import {CasesApi, UnifiedWarningDTO} from '@/api/member/cases'
const router = useRouter()

// 定义组件名称
defineOptions({name: 'PersonWarnComponent'})

// ======================== 类型定义 ========================
interface MapPolygon {
  id?: string
  configId: string
  name: string
  strokeColor: string
  strokeWeight: number
  fillColor: string
  fillOpacity: number
  roomLevel: 13
  sortOrder: number
  points: Array<{ ringIndex: number; lng: number; lat: number; pointIndex: number }>
  coordinates: number[][][]
  area?: number
  pointCount?: number
}

interface JudgeResult {
  isInside: boolean
  insidePolygons?: Array<{ id: string; name: string; configId: string; configName: string }>
}

// ======================== 列表相关逻辑 ========================
const loading = ref(true)
const configLoading = ref(false)
const list = ref<UnifiedWarningDTO[]>([])
const total = ref(0)

// 预警配置下拉框选项
const configOptions = ref<WarnConfigRespVO[]>([])

const {personId} = defineProps({
  personId: {
    type: [String, Array],
    required: true
  }
});

// 1. 单条标记为已读
const handleMarkSingleRead = async (row) => {
  try {
    // 调用后端接口：标记该条记录为已读（传入row.id等关键参数）
    if (row.warnType === 2) {
      await WarningGatherPersonApi.markSingleRead(row.id)
    }else {
      await WarningIndividualApi.markSingleRead(row.id)
    }
    // 前端临时更新状态（接口成功后）
    row.isRead = true
    ElMessage.success('标记已读成功')
  } catch (error) {
    // 先判断error是否为Error类型
    const errorMsg = error instanceof Error ? error.message : '网络异常'
    ElMessage.error('标记已读失败：' + errorMsg)
  }
}

// 2. 全部标记为已读
const handleMarkAllRead = async () => {
  const unreadRows = list.value.filter(row => !row.isRead)
  if (!unreadRows.length) {
    ElMessage.info('已无未读记录')
    return
  }

  try {
    // 1. 提取未读记录的id列表
    const gatherRows = list.value.filter(row => row.warnType === 2)
    const gatherUnreadIds = gatherRows.map(row => row.id)
    const notGatherRows = list.value.filter(row => row.warnType !== 2)
    const notGatherUnreadIds = notGatherRows.map(row => row.id)

    // 2. 调用批量接口（关键修正：使用markBatchRead而非markSingleRead）
    if(gatherUnreadIds.length > 0){
      await WarningGatherPersonApi.markBatchRead(gatherUnreadIds)
      // 3. 前端更新状态
      gatherRows.forEach(row => {
        row.isRead = true
      })
    }
    if(notGatherUnreadIds.length > 0){
      await WarningIndividualApi.markBatchRead(notGatherUnreadIds)
      // 3. 前端更新状态
      notGatherRows.forEach(row => {
        row.isRead = true
      })
    }
    ElMessage.success(`成功标记${gatherUnreadIds.length + notGatherUnreadIds.length}条记录为已读`)
  } catch (error) {
    const errorMsg = error instanceof Error ? error.message : '批量标记已读失败'
    ElMessage.error(errorMsg)
  }
}

const queryFormRef = ref<InstanceType<any> | null>(null)

/** 获取预警配置下拉框数据 */
const getConfigOptions = async () => {
  configLoading.value = true
  try {
    // 查询聚集预警类型的配置（warnType=2）
    const params: WarnConfigListVo = {
      warnType: 1
    }
    const data = await WarningGatherApi.getConfigSelect(params)
    configOptions.value = data || []
  } catch (error) {
    const errorMsg = error instanceof Error ? error.message : '网络异常'
    ElMessage.error('获取预警配置失败：' + errorMsg)
    console.error('获取预警配置失败:', error)
  } finally {
    configLoading.value = false
  }
}

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  personId: personId,
  warnType: undefined,
  configId: undefined
})

// 获取列表数据
const getList = async () => {
  loading.value = true
  try {
    const data = await CasesApi.getPersonLatestWarnPage(queryParams)
    list.value = data.list
    total.value = data.total
  } catch (error) {
    ElMessage.error('获取预警列表失败')
    console.error('获取列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索和重置
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// ======================== 地图相关状态 ========================
const showMapDialog = ref(false)
const currentWarning = ref<WarningIndividualVO | null>(null)
const selectedConfigId = ref('')
const mapRef = ref<HTMLDivElement | null>(null)
const mapDialogRef = ref<InstanceType<any> | null>(null)
let mapInstance: L.Map | null = null
let polygonLayer: L.FeatureGroup<L.Polygon> | null = null
let warningMarker: L.Marker | null = null

// 多边形相关状态
const polygons = ref<MapPolygon[]>([])
const selectedPolygon = ref<MapPolygon | null>(null)
const isDrawing = ref(false)
const areaUnit = ref<'sqm' | 'sqkm' | 'sqmi'>('sqm')

const judgeResult = ref<JudgeResult | null>(null)
const showJudgeResult = ref(false)
import {useMessage} from "@/hooks/web/useMessage";
import {WarningGatherPersonApi} from "@/api/member/warninggatherperson";
const message = useMessage()
const isLoadingPolygons = ref(false)

// ======================== 工具方法 ========================
/** 显示状态消息 */
const setMessage = (text: string, duration = 3000) => {
  ElMessage({
    message: text,
    type: 'info',
    duration
  })
}

/** 计算多边形面积（球面积分算法） */
const calculatePolygonArea = (points: [number, number][]): number => {
  if (points.length < 3) return 0

  const R = 6378137 // 地球半径（米）
  let area = 0
  const radPoints = points.map(([lng, lat]) => [lng * Math.PI / 180, lat * Math.PI / 180])
  const n = radPoints.length

  for (let i = 0; i < n; i++) {
    const j = (i + 1) % n
    const [lng1, lat1] = radPoints[i]
    const [lng2, lat2] = radPoints[j]
    const dLng = lng2 - lng1
    area += dLng * (2 + Math.sin(lat1) + Math.sin(lat2))
  }

  return Math.abs(area * R * R / 2)
}

/** 格式化面积显示 */
const formatArea = (area: number): string => {
  switch (areaUnit.value) {
    case 'sqkm':
      return (area / 1000000).toFixed(6)
    case 'sqmi':
      return (area / 2589988.11).toFixed(6)
    default:
      return area.toFixed(2)
  }
}

/** 获取面积单位标签 */
const getAreaUnitLabel = (): string => {
  switch (areaUnit.value) {
    case 'sqkm':
      return '平方公里'
    case 'sqmi':
      return '平方英里'
    default:
      return '平方米'
  }
}

// ======================== 地图操作方法 ========================
/** 初始化地图 */
const initMap = (centerLng: number, centerLat: number, zoom = 15) => {
  if (!mapRef.value) {
    setMessage('地图容器未找到', 3000)
    return
  }

  // 清除现有地图实例
  if (mapInstance) {
    mapInstance.remove()
  }

  // 创建新地图实例（定位到预警点）
  mapInstance = L.map(mapRef.value, {
    minZoom: 10,
    maxZoom: 18,
    crs: L.CRS.EPSG3857,
    attributionControl: true
  }).setView([centerLat, centerLng], zoom)

  // 加载离线地图瓦片
  // 加载地图瓦片
  L.tileLayer(import.meta.env.VITE_MAP_TILE_URL, {
    errorTileUrl: '',
    attribution: '地图数据 © 高德地图',
    tileSize: 256,
    zoomOffset: 0
  }).addTo(mapInstance);
  // L.tileLayer('http://localhost:8000/map/{z}/{x}/{y}/tile.png', {
  //   errorTileUrl: '',
  //   attribution: '地图数据 © 高德地图',
  //   tileSize: 256,
  //   zoomOffset: 0
  // }).addTo(mapInstance)

  // 初始化多边形图层
  polygonLayer = L.featureGroup<L.Polygon>().addTo(mapInstance)
  // initDrawControl()

  // 添加预警点标记
  addWarningMarker()
}

/** 添加预警点标记 */
const addWarningMarker = () => {
  if (!mapInstance || !currentWarning.value) return

  const {lng, lat, personName, warningTime, warningContent, fenceType} = currentWarning.value
  // 清除现有预警点标记
  if (warningMarker) {
    mapInstance.removeLayer(warningMarker)
  }

  // 转换fenceType为文字描述
  const fenceTypeText = fenceType === 1 ? '禁入围栏' :
    fenceType === 2 ? '禁出围栏' :
      `未知类型(${fenceType})`

  const warnTimeText = formatToDateTime(warningTime)

  // 自定义预警点图标
  const warningIcon = L.divIcon({
    className: 'warning-point-marker',
    html: `
      <div style="
        width: 40px;
        height: 40px;
        background-color: #ff4d4f;
        border: 2px solid white;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        box-shadow: 0 2px 10px rgba(255, 77, 79, 0.6);
      ">
        <i class="el-icon-user" style="font-size: 20px;"></i>
      </div>
      <div style="
        position: absolute;
        bottom: -90px;
        left: 50%;
        transform: translateX(-50%);
        background-color: white;
        padding: 2px 6px;
        border-radius: 4px;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        white-space: nowrap;
        font-size: 12px;
        color: #333;
      ">
        ${personName}
      </div>
    `,
    iconSize: [40, 120], // 增加图标高度以适应更长的标签
    iconAnchor: [20, 40]
  })

  // 创建标记并添加到地图
  warningMarker = L.marker([lat, lng], {icon: warningIcon, zIndexOffset: 3000}).addTo(mapInstance)
  // 绑定弹窗，包含新增的三个内容
  warningMarker.bindPopup(`
    <div style="width: 280px; padding: 5px 0;">
      <p><strong>人员姓名：</strong>${personName}</p>
      <p><strong>预警时间：</strong>${warnTimeText || '无数据'}</p>
      <p><strong>预警内容：</strong>${warningContent || '无数据'}</p>
      <p><strong>预警类型：</strong>${fenceTypeText}</p>
    </div>
  `).openPopup()
}

/** 加载围栏多边形 */
const loadPolygonsByConfigId = async (configId: string) => {
  if (!configId) {
    setMessage('预警条件ID为空，无法加载围栏', 3000)
    return Promise.reject(new Error('configId is empty'))
  }

  if (isLoadingPolygons.value) return Promise.resolve()
  isLoadingPolygons.value = true

  try {
    console.log('正在加载围栏数据...')
    const res = await MapPolygonApi.getPolygonsByConfigId(configId)

    if (res?.length) {
      polygons.value = res.map((poly: any) => ({
        ...poly,
        pointCount: poly.points?.length || 0,
        area: poly.area || calculatePolygonArea(
          poly.points
            ?.filter((p: any) => p.ringIndex === 0)
            .sort((a: any, b: any) => a.pointIndex - b.pointIndex)
            .map((p: any) => [p.lng, p.lat] as [number, number]) || []
        )
      }))

      renderPolygons()
      // setMessage(`已加载${res.length}个围栏`, 3000)
    } else {
      polygons.value = []
      polygonLayer?.clearLayers()
      setMessage('当前预警条件下无围栏数据', 3000)
    }

    return Promise.resolve()
  } catch (error) {
    setMessage('加载围栏失败', 3000)
    console.error('加载多边形错误:', error)
    return Promise.reject(error)
  } finally {
    isLoadingPolygons.value = false
  }
}

/** 渲染多边形到地图 */
const renderPolygons = () => {
  if (!mapInstance || !polygonLayer) return

  // 清空并重新渲染多边形图层
  polygonLayer.clearLayers()

  polygons.value.forEach(poly => {
    const ringMap: Record<number, L.LatLng[]> = {}
    poly.points.forEach((p: any) => {
      const ringIndex = p.ringIndex || 0
      if (!ringMap[ringIndex]) ringMap[ringIndex] = []
      ringMap[ringIndex].push(L.latLng(p.lat, p.lng))
    })

    const latLngs = Object.keys(ringMap)
      .sort((a, b) => Number(a) - Number(b))
      .map(key => ringMap[Number(key)])

    // 错误1修复：使用非空断言操作符!，因为已在函数开头检查过polygonLayer不为null
    const layer = L.polygon(latLngs, {
      color: poly.strokeColor,
      weight: poly.strokeWeight,
      fillColor: poly.fillColor,
      fillOpacity: poly.fillOpacity,
      zIndexOffset: poly.roomLevel || 0
    }).addTo(polygonLayer!)

    layer.bindPopup(`<b>${poly.name}</b><br>面积: ${formatArea(poly.area || 0)} ${getAreaUnitLabel()}`)
  })

  // 调整视野（包含预警点和所有多边形）
  if (currentWarning.value) {
    // 错误2修复：明确使用L.latLng创建坐标点，而不是使用数组
    const bounds = L.latLngBounds([
      L.latLng(currentWarning.value.lat, currentWarning.value.lng),
      ...polygons.value.flatMap(poly =>
        poly.points.map(p => L.latLng(p.lat, p.lng))
      )
    ])
    mapInstance.fitBounds(bounds, {padding: [50, 50], maxZoom: 15})
  }
}

// ======================== 地图弹窗控制 ========================

// 处理详情点击事件
const handleDetailClick = (row) => {
  if (row.warnType === 1) {
    handleViewMap(row); // 类型1调用地图查看
  } else if (row.warnType === 2) {
    openGatherDetail(row); // 类型2调用聚集详情
  }
  // 其他类型不执行任何操作
};

/** 打开地图详情弹窗 */
const handleViewMap = (row: WarningIndividualVO) => {
  if (!row.lng || !row.lat) {
    ElMessage.warning('当前预警点坐标缺失，无法显示地图')
    return
  }

  // 赋值当前预警数据
  currentWarning.value = row
  selectedConfigId.value = row.warningConditionId.toString()
  showMapDialog.value = true

  // 弹窗渲染完成后初始化地图
  nextTick(() => {
    if (row.warnType === 1) {
      // 围栏地图
      initMap(row.lng, row.lat)
      // 加载对应预警条件的围栏
      loadPolygonsByConfigId(selectedConfigId.value)
    } else {

    }

  })
}

/** 打开聚集预警详情页，传递完整行记录 */
const openGatherDetail = (row: WarningIndividualVO) => {
  try {
    // 1. 再次确认id存在（排除id类型问题）
    if (row.gatherId === undefined || row.gatherId === null) {
      throw new Error('记录ID不存在，无法打开详情')
    }

    // 2. 单独序列化row，确保无异常（排查序列化失败）
    let rowDataStr: string;
    try {
      rowDataStr = JSON.stringify(row);
      // console.log('序列化后的数据:', rowDataStr); // 确认序列化结果
    } catch (serialError) {
      throw new Error(`数据序列化失败: ${(serialError as Error).message}`);
    }

    // 3. 编码并传递参数
    router.push({
      name: 'WarningGatherPerson',
      params: {
        id: row.gatherId.toString(), // 匹配路由的:id参数
      },
      query: {
        rowData: encodeURIComponent(rowDataStr) // 确保添加到query
      }
    });

  } catch (error) {
    console.error('打开详情失败:', error);
    message.error(`打开详情失败: ${(error as Error).message}`);
  }
};

/** 监听地图弹窗关闭，清理资源 */
watch(showMapDialog, (newVal) => {
  if (!newVal) {
    cleanupMapResources()
  }
})

/** 清理地图资源 */
const cleanupMapResources = () => {
  // 清除地图实例
  if (mapInstance) {
    mapInstance.remove()
    mapInstance = null
  }
  // 重置状态
  polygons.value = []
  selectedPolygon.value = null
  judgeResult.value = null
  showJudgeResult.value = false
  isDrawing.value = false
  warningMarker = null
  currentWarning.value = null
  selectedConfigId.value = ''
}

/** 窗口大小变化时调整地图 */
const handleResize = () => {
  mapInstance?.invalidateSize()
}

// ======================== 生命周期 ========================
onMounted(() => {
  // 先加载配置下拉框，再加载列表数据
  getConfigOptions().then(() => {
    getList()
  })
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  cleanupMapResources()
})
</script>

<style scoped>
/* 基础列表样式 */

/* 地图弹窗样式 */
.draggable-dialog {
  position: fixed !important;
  top: 50% !important;
  left: 50% !important;
  transform: translate(-50%, -50%) !important;
  margin: 0 !important;
  transition: none !important;
}

.draggable-dialog .el-dialog__header {
  cursor: move;
  user-select: none;
}

.draggable-dialog .el-dialog__body {
  cursor: default;
  padding: 0 !important;
}

.fixed-size-dialog {
  display: flex;
  flex-direction: column;
  max-height: 90vh !important;
  overflow: hidden;
}

.map-dialog-container {
  position: relative;
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  height: 100%;
}

.map {
  width: 100%;
  flex: 1;
  border-radius: 6px;
  min-height: 500px;
}

/* 地图控制按钮组 */
.map-controls {
  position: absolute;
  top: 10px;
  right: 10px;
  display: flex;
  flex-direction: column;
  gap: 10px;
  z-index: 1000;
}

.control-btn {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  border: none;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
  background-color: white;
  color: #333;
}

.control-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25);
}

.control-btn.active {
  background-color: #4ecdc4;
  color: white;
}

.save-btn {
  background-color: #42b983;
  color: white;
}

.clear-btn {
  background-color: #f44336;
  color: white;
}

.load-btn {
  background-color: #17a2b8;
  color: white;
}

.judge-btn {
  background-color: #f39c12;
  color: white;
}

/* 多边形属性面板 */
.polygon-info {
  position: absolute;
  bottom: 20px;
  left: 20px;
  background-color: white;
  padding: 15px;
  border-radius: 6px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  width: 300px;
  z-index: 1000;
  max-height: 70%;
  overflow-y: auto;
}

/* 判断结果面板 */
.point-judge {
  position: absolute;
  top: 10px;
  right: 70px;
  background-color: white;
  padding: 15px;
  border-radius: 6px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  width: 320px;
  z-index: 1000;
  max-height: 80vh;
  overflow-y: auto;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.close-btn {
  background: none;
  border: none;
  color: #666;
  cursor: pointer;
  font-size: 16px;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.close-btn:hover {
  background-color: #f0f0f0;
  color: #f44336;
}

.custom-close-icon {
  position: relative;
}

.custom-close-icon::before,
.custom-close-icon::after {
  content: '';
  position: absolute;
  width: 2px;
  height: 16px;
  background-color: #666;
}

.custom-close-icon::before {
  transform: rotate(45deg);
}

.custom-close-icon::after {
  transform: rotate(-45deg);
}

.custom-close-icon:hover::before,
.custom-close-icon:hover::after {
  background-color: #f44336;
}

/* 预警点标记样式 */
:deep(.warning-point-marker) {
  display: block !important;
  visibility: visible !important;
  z-index: 3000 !important;
}

:deep(.leaflet-marker-icon.warning-point-marker) {
  border: none !important;
  background: transparent !important;
}

/* 表单样式 */
.form-group {
  margin-bottom: 12px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
}

.form-control {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
}

.coordinate-display {
  padding: 8px 12px;
  background-color: #f9f9f9;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-family: monospace;
}

/* 判断结果样式 */
.judge-result {
  margin-top: 15px;
  padding-top: 10px;
  border-top: 1px dashed #eee;
}

.result-label {
  font-weight: 500;
  margin-bottom: 8px;
}

.result-inside {
  color: #f56c6c;
  font-weight: 500;
}

.result-outside {
  color: #67c23a;
  font-weight: 500;
}

.polygon-list {
  margin-top: 5px;
  padding-left: 20px;
  color: #606266;
}

/* 状态提示 */
.status-message {
  position: absolute;
  bottom: 20px;
  right: 20px;
  padding: 10px 15px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  border-radius: 4px;
  z-index: 1000;
}

/* 按钮样式 */
.btn {
  padding: 8px 16px;
  border-radius: 4px;
  border: none;
  cursor: pointer;
  font-size: 14px;
  display: inline-flex;
  align-items: center;
  margin-right: 8px;
  margin-top: 10px;
}

.btn-primary {
  background-color: #42b983;
  color: white;
}

.btn-danger {
  background-color: #f44336;
  color: white;
}

.btn-secondary {
  background-color: #e5e7eb;
  color: #374151;
}

/* 分页样式 */
:deep(.el-pagination) {
  margin-top: 15px;
  text-align: right;
}

/* 弹窗结果样式 */
:deep(.popup-result) {
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px solid #eee;
}

:deep(.leaflet-popup-tip-container) {
  bottom: 0;
}

:deep(.leaflet-popup-content-wrapper) {
  margin-bottom: 20px;
}
</style>
